package com.hfi.restful.security;

import com.hfi.restful.web.register.CustomUser;
import com.hfi.restful.web.register.CustomUserRepository;
import com.hfi.security.core.exception.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author ChangLiang
 * @date 2019/8/5
 */
@Component
public class HfiUserDetailService implements UserDetailsService, SocialUserDetailsService {

    public static final String ROLE_REGISTER_STRING = "1";
    public static final String ROLE_REAL_NAME_STRING = "2";
    public static final String ROLE_REAL_NAME_FACE_STRING = "3";
    @Autowired
    private CustomUserRepository customUserRepository;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 根据手机号查找用户
     * @param identity
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String identity) throws UsernameNotFoundException {
        logger.info("登录手机号/用户名：" + identity);
        // 根据用户名查找用户

        // 根据查找到的用户信息判断用户是否被冻结

        // 这里返回的User可以是我们自定义的

        // AuthorityUtils.commaSeparatedStringToAuthorityList 是将一个用comma分割的字符串 convert to AuthorityList
        CustomUser customUser = customUserRepository.getByMobile(identity);
        if (customUser == null) {
            customUser = customUserRepository.getByCustName(identity);
            if (customUser == null) {
                // 发现refresh_token要使用authentication中的唯一标识
                customUser = customUserRepository.getByCustUserId(Long.valueOf(identity));
                if (customUser == null) {
                    throw new UsernameNotFoundException(ErrorCode.USER_NOT_EXIST.memo);
                }
            }
        }
        // 无论是用户名 还是 手机号登录 均使用custUserId作为唯一标识
        // TODO:这里的authorities collection应该是查询数据库获取 第三方client(app或部委办局)的权限
        User user = new User(String.valueOf(customUser.getCustUserId()), customUser.getPasswd(), true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(convertUserLevel2Role(customUser.getUserLevel().toString())));
        return user;
    }

    private String convertUserLevel2Role(String userLevel) {
        if (StringUtils.equals(userLevel, ROLE_REGISTER_STRING)) {
            return "ROLE_REGISTER";
        } else if (StringUtils.equals(userLevel, ROLE_REAL_NAME_STRING)) {
            return "ROLE_REAL_NAME";
        } else if (StringUtils.equals(userLevel, ROLE_REAL_NAME_FACE_STRING)) {
            return "ROLE_REAL_NAME_FACE";
        } else {
            return "ROLE_ANONYMOUS";
        }
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        logger.info("登录userId：" + userId);
        CustomUser customUser = customUserRepository.getByCustUserId(Long.valueOf(userId));
        if (customUser == null) {
            throw new UsernameNotFoundException(ErrorCode.USER_NOT_EXIST.memo);
        }
        SocialUser user = new SocialUser(userId, customUser.getPasswd(), true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(convertUserLevel2Role(customUser.getUserLevel().toString())));
        return user;
    }
}
